<template>
  <div>
    <Temp title="添加漫游路径">
      <div class="add-fly-line">
        <div class="content">
          <el-input
            clearable
            size="small"
            v-model="flyLineName"
            placeholder="请输入路径名称"
          />
          <el-scrollbar ref="scrollbar">
            <div class="point-list">
              <AddPointItem
                v-for="(item, index) in selectedPoints"
                :key="item.id"
                :index="index"
                @deletePoint="onPointDelete"
              />
            </div>
            <el-button
              icon="el-icon-plus"
              type="text"
              @click="addPoint"
            ></el-button>
          </el-scrollbar>
        </div>
        <div class="bottom">
          <el-button type="normal" @click="cancel"
            >取消</el-button
          >
          <el-button type="primary" @click="save"
            >保存</el-button
          >
        </div>
      </div>
    </Temp>
  </div>
</template>

<script>
import Temp from '@/components/utool/components/temp'
import AddPointItem from '@/components/addPointItem'
import { getAction } from '@/utils/helper'
import CreateFlyLineXml from './fly-line-xml.js'

/**
 * 标点
 */
const markers = []

let mapViewer = null

let handler = null

let createXml = null

export default {
  inject: ['viewerId'],
  components: {
    Temp,
    AddPointItem
  },
  data() {
    return {
      // 选取的点
      selectedPoints: [],
      nameDialogVisible: false,
      flyLineName: ''
    }
  },
  async created() {
    const { viewer } = await getAction(this.viewerId)
    mapViewer = viewer
  },
  destroyed() {
    this.offMapClickListener()
    mapViewer.entities.removeAll()
  },
  methods: {
    offMapClickListener() {
      // mapViewer.mars.off(mars3d.event.click)
      if (handler) {
        handler.removeInputAction(
          Cesium.ScreenSpaceEventType.LEFT_UP
        )
      }
      mapViewer.enableCursorStyle = true
    },
    addPoint() {
      this.offMapClickListener()
      if (!handler) {
        handler = new Cesium.ScreenSpaceEventHandler(
          mapViewer.scene.canvas
        )
      }
      mapViewer.enableCursorStyle = false
      mapViewer._element.style.cursor = ''
      handler.setInputAction((e) => {
        this.offMapClickListener()

        const windowPosition = mapViewer.camera.getPickRay(
          e.position
        )
        const cartesian = mapViewer.scene.globe.pick(
          windowPosition,
          mapViewer.scene
        )
        if (cartesian) {
          const cartographic =
            Cesium.Cartographic.fromCartesian(cartesian)
          const longitude = Number(
            Cesium.Math.toDegrees(
              cartographic.longitude
            ).toFixed(6)
          )
          const latitude = Number(
            Cesium.Math.toDegrees(
              cartographic.latitude
            ).toFixed(6)
          )
          const height = Number(
            cartographic.height.toFixed(1)
          )
          // const wgsPoint = mapViewer.mars.point2wgs({ x: longitude, y: latitude }) // 坐标转换为wgs
          // longitude = wgsPoint.x
          // latitude = wgsPoint.y
          const pointItem = {
            x: longitude,
            y: latitude,
            z: height
          }
          this.addMarker(pointItem)
        }
      }, Cesium.ScreenSpaceEventType.LEFT_UP)

      // this.offMapClickListener()
      // mapViewer.mars.on(mars3d.event.click, (event) => {
      //   this.offMapClickListener()
      //
      //   const cartesian = mars3d.point.getCurrentMousePosition(mapViewer.scene, event.position)
      //   if (cartesian) {
      //     const cartographic = Cesium.Cartographic.fromCartesian(cartesian)
      //     let longitude = Number(Cesium.Math.toDegrees(cartographic.longitude).toFixed(6))
      //     let latitude = Number(Cesium.Math.toDegrees(cartographic.latitude).toFixed(6))
      //     const height = Number(cartographic.height.toFixed(1))
      //     const wgsPoint = mapViewer.mars.point2wgs({ x: longitude, y: latitude }) // 坐标转换为wgs
      //     longitude = wgsPoint.x
      //     latitude = wgsPoint.y
      //     const pointItem = { x: longitude, y: latitude, z: height }
      //     this.addMarker(pointItem)
      //   }
      // })
    },
    onPointDelete(index) {
      this.selectedPoints.splice(index, 1)
      this.removeMarker(index)
    },
    addMarker(point, isCenter) {
      const position = Cesium.Cartesian3.fromDegrees(
        point.x,
        point.y,
        point.z
      )
      const marker = mapViewer.entities.add({
        name: '坐标拾取',
        position: position,
        point: {
          color: Cesium.Color.fromCssColorString('#3388ff'),
          pixelSize: 10,
          outlineColor:
            Cesium.Color.fromCssColorString('#ffffff'),
          outlineWidth: 2,
          disableDepthTestDistance: Number.POSITIVE_INFINITY // 一直显示，不被地形等遮挡
        }
      })
      markers.push(marker)
      this.selectedPoints.push({
        stopName: this.generateUUID(),
        point: [point.x, point.y, point.z],
        heading: mapViewer.camera.heading,
        tilt: mapViewer.camera.pitch,
        speed: 0,
        stopPlayMode: 'StopPause',
        surroundDuration: 1,
        waitTime: 0
      })
      // this.selectedPoints.push({
      //   id: this.generateUUID(),
      //   cartesian: position,
      //   longitude: point.x,
      //   latitude: point.y,
      //   height: point.z
      // })
      this.$refs.scrollbar.wrap.scrollTop = 0

      // if (isCenter) {
      //   mapViewer.camera.mars.centerPoint(position, {
      //     radius: 5000 // 距离目标点的距离
      //   })
      // }
    },
    removeMarker(index) {
      mapViewer.entities.remove(markers[index])
      markers.splice(index, 1)
    },
    cancel() {
      this.$bus.$emit('hideAddFlyLine')
    },
    save() {
      if (!this.flyLineName) {
        this.$message('请输入漫游路径名称')
      } else if (this.selectedPoints.length < 2) {
        this.$message('至少添加两个点')
      } else {
        Cesium.when(
          mapViewer.scene.outputSceneToFile(),
          (base64) => {
            if (!createXml) {
              createXml = new CreateFlyLineXml()
            }
            const route = {
              routeName: this.flyLineName,
              speed: 50,
              isAlongLine: 'False',
              routeStops: this.selectedPoints
            }
            const xml = createXml.createXMLflyLine(route)
            let savedData = this.getLocalCustomFlyLineData()
            if (Array.isArray(savedData)) {
              savedData.push({
                id: this.generateUUID(),
                // img: base64,
                name: this.flyLineName,
                data: xml
              })
            } else {
              savedData = [
                {
                  id: this.generateUUID(),
                  // img: base64,
                  name: this.flyLineName,
                  data: xml
                }
              ]
            }
            this.saveLocalCustomFlyLineData(savedData)
            this.$bus.$emit('haveAddedCustomFlyLine')
            this.cancel()
          }
        )
      }
    },
    /**
     * 获取localStorage中的漫游路径数据
     */
    getLocalCustomFlyLineData() {
      const localCustomFlyLineData =
        window.localStorage.getItem('customFlyLineData')
      if (localCustomFlyLineData) {
        return JSON.parse(localCustomFlyLineData)
      } else {
        return null
      }
    },
    saveLocalCustomFlyLineData(data) {
      window.localStorage.setItem(
        'customFlyLineData',
        JSON.stringify(data)
      )
    }
  }
}
</script>

<style lang="scss">
.add-fly-line {
  width: 250px;
  height: 331px;
  display: flex;
  flex-direction: column;
  align-items: center;
  background-color: #193b51;
  border-radius: 0 0 8px 8px;

  .content {
    width: 100%;
    padding: 10px 20px 0 20px;
    flex: 1;
    display: flex;
    flex-direction: column;
    align-items: center;
    overflow-y: hidden;

    .el-input {
      width: 200px;
      margin-bottom: 10px;

      &__inner {
        background-color: #0c87a8;
        color: white;
      }
    }

    .el-scrollbar {
      flex: 1;
      height: 100%;
      width: 100%;

      .el-scrollbar__wrap {
        overflow-x: hidden;

        .el-scrollbar__view {
          display: flex;
          flex-direction: column;
          align-items: center;
          padding-right: 10px;

          .point-list {
            width: 100%;
            display: flex;
            flex-direction: column;

            .add-point-item {
              margin-bottom: 14px;
            }

            .add-point-item:last-of-type {
              margin-bottom: 0;
            }
          }

          .el-button {
            padding: 5px;
          }

          .el-button--text {
            color: white;
          }
        }
      }
    }
  }

  .bottom {
    display: flex;
    align-items: center;
    margin: 10px 0;

    button {
      padding: 5px 10px;
    }
  }
}
</style>
